package middleware

import (
	"log"
	"net/http"
	"strings"
)

//CORSMiddleware CORS跨域中间件
type CORSMiddleware struct {
	next http.Handler
}

func (mw *CORSMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//非ajax请求无需处理跨域问题
	xReq := r.Header.Get("X-Requested-With")
	if xReq == "" || !strings.EqualFold(xReq, "XMLHttpRequest") {
		mw.next.ServeHTTP(w, r)
		return
	}

	log.Println("进入跨域中间件")
	if origin := r.Header.Get("Origin"); origin != "" {
		log.Printf("处理跨域：%v", origin)
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "*")
	}

	//对于预检查OPTIONS请求，直接返回
	if r.Method == "OPTIONS" {
		log.Printf("收到预检请求")
		return
	}
	mw.next.ServeHTTP(w, r)
}

func NewCORSMiddleware(handler http.Handler) *CORSMiddleware {
	return &CORSMiddleware{next: handler}
}
